package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"goods-master2/cache"
	"goods-master2/models"
	"strconv"
	"time"
)

func ListGoods(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var goods []models.Goods

	redis_key := "goods_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&goods)
		jsonData, _ := json.Marshal(goods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goods)
	}

	var total int64
	models.DB.Model(&goods).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  goods,
		"total": total,
	})
	return
}

func FindGoods(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	goods_name := c.Query("goods_name")
	offset := (page - 1) * size

	var goods []models.Goods

	redis_key := "goods_page_name_" + strconv.Itoa(page) + goods_name
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Where("goods_name = ?", goods_name).Find(&goods)
		jsonData, _ := json.Marshal(goods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goods)
	}

	var total int64
	models.DB.Model(&goods).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  goods,
		"total": total,
	})
	return
}
